package com.example.utilDao;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.db.MyDataBaseOpenHelper;
import com.example.entiy.Student;

import java.util.ArrayList;
import java.util.List;
//数据库工具类,对数据库的各种实际操作


public class StudentDao {
    //获取数据库帮助类
    private MyDataBaseOpenHelper helper = null;

    public StudentDao(Context context) {
        helper = new MyDataBaseOpenHelper(context);
    }


    //添加一个学生
    public void studentAdd(String name ,String sex){
        //得到一个数据库
        SQLiteDatabase db = helper.getWritableDatabase();
        String sql = "insert into student(name,sex) values(?,?);";
        Object object[] =new Object[]{name,sex};
        db.execSQL(sql,object);
        db.close();
    }

    //删除一个学生
    public void studentDelete(String name){
        //得到一个数据库
        SQLiteDatabase db = helper.getWritableDatabase();
        String sql = "delete from student where name = ?";
        Object object[] =new Object[]{name};
        db.execSQL(sql,object);
        db.close();
    }

    //更新一个学生数据 修改性别,不允许修改姓名
    public void studentUpdate(String name,String sex){
        //得到一个数据库
        SQLiteDatabase db = helper.getWritableDatabase();
        String sql = "update student set sex = ? where name = ? ;";
        Object object[] =new Object[]{sex,name};
        db.execSQL(sql,object);
        db.close();
    }

    //查询全部学生
    public List<Student> studentQueryAll(){
        //得到一个数据库
        SQLiteDatabase db = helper.getWritableDatabase();
        String sql = "select name,sex from student;";
        Cursor cursor = db.rawQuery(sql,null);//cursor 相当于javaweb的结果集
        List<Student> students = new ArrayList<Student>();
        Student student = null;
        while(cursor.moveToNext()){
            student = new Student(cursor.getString(0),cursor.getString(1));
            students.add(student);
        }
        cursor.close();
        db.close();
        return students;
    }


//    根据姓名查询学生性别
    public String studentQueryByname(String name){
        //得到一个数据库
        SQLiteDatabase db = helper.getWritableDatabase();
        String sql = "select sex from student where name = ? ;";
        Cursor cursor= db.rawQuery(sql,new String[]{name});
        String str =null;
        if(cursor.moveToNext()){
            str = cursor.getString(0);
        }
        cursor.close();
        db.close();
        return str;
}
}
